﻿using DevExpress.Utils;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Views.Grid;
using Lamex.Base;
using Lamex.Interface;
using Lamex.Library;
using Lamex.Library.CommonClass;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;


namespace Lamex.mMachine
{
    public partial class frmMAC_File_Path_Info : frmBaseDataForm
    {
        static string strPath = "";
        static string strPath1 = "";
        static string strPath2 = "";
        public frmMAC_File_Path_Info()
        {
            InitializeComponent();
            // InitializeForm();
            //frmGridViewCust.RegisterGrid(gridView1);
            GetSearchLookUpEdit();
            //DevStyle.SetGridControlLayout(gridControl1, false);//表格设置-右键功能   
        }

        private void frmMAC_File_Path_Info_Load(object sender, EventArgs e)
        {
            try { this.InitButtons(); } catch { }//初始化标准功能，因要应用于RibbonForm，所以加入异常处理
        }
        protected override void InitializeForm()
        {
            _SummaryView = new DevGridView(gridView1);
            gridView1.DoubleClick += new EventHandler(OnGridViewDoubleClick); //主表DoubleClict
            frmGridViewCust.RegisterGrid(gridView1);
            DevStyle.SetGridControlLayout(gridControl1, false);//表格设置   

            DevStyle.SetSummaryGridViewLayout(gridView1);
            DevStyle.SetDetailGridViewLayout(gridView1);
            ShowSummary(); //下载显示数据.
            tpSummary = xtraTabPage1;
            tcBusiness = xtraTabControl1;
            tpSummary.PageVisible = true;
            //tpDetail.PageVisible = false;
            tcBusiness.ShowTabHeader = DefaultBoolean.True;
            tcBusiness.SelectedTabPage = tpSummary;
        }
        private void ShowSummary()
        {
            try
            {
                xtraTabPage2.PageEnabled = false;
                xtraTabPage1.PageEnabled = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        public override void DoView(Lamex.Interface.IButtonInfo sender)
        {
            string sqlWhere = "";
            string sql = @"	  SELECT IDNO
	  ,PA.[MACHINE_NO]
	  ,BA.MACHINE_NAME
      ,[MACHINE_DWG_PATH]
      ,[USE_RULES_PATH]
      ,[MACHINE_INFO_PATH]
      ,PA.[UPDATE_TIME]
      ,PA.[UPDATE_USER]
  FROM [LamexMESManager].[dbo].[FAMA_File_Path_Info] 
  PA LEFT JOIN [LamexMESManager].[dbo].[FAMA_Account_Basic_Info] BA ON PA.MACHINE_NO=BA.MACHINE_NO
   WHERE 1=1";
            if (!string.IsNullOrEmpty(txtMACHINE_NO.Text))
            {
                sqlWhere += " and MACHINE_NO like '%" + txtMACHINE_NO.Text + "%'";
            }
            //if (!string.IsNullOrEmpty(txtASSET_NO.Text))
            //{
            //    sqlWhere += " and ASSET_NO like '%" + txtASSET_NO.Text + "%'";
            //}
            //if (!string.IsNullOrEmpty(txtINVENTORY_NO.Text))
            //{
            //    sqlWhere += " and INVENTORY_NO like '%" + txtINVENTORY_NO.Text + "%'";
            //}

            sql = sql + sqlWhere + " order by UPDATE_TIME desc ";
            DataTable dt = BaseBuildSql.GetDataTableBySql(sql);
            //foreach (DataRow row in dt.Rows)
            //{
            //    row["MACHINE_DWG_PATH"] = ((String)row["MACHINE_DWG_PATH"]).Replace(@";", Environment.NewLine);
            //    row["USE_RULES_PATH"] = ((String)row["USE_RULES_PATH"]).Replace(@";", Environment.NewLine);
            //    row["MACHINE_INFO_PATH"] = ((String)row["MACHINE_INFO_PATH"]).Replace(@";", Environment.NewLine);
            //}
            //  DoBindingSummaryGrid(dt);
            gridControl1.DataSource = dt;
            gridView1.BestFitColumns();
            this.gridView1.OptionsView.ColumnAutoWidth = false;
            base.DoView(sender);

        }
        //新增
        public override void DoAdd(Lamex.Interface.IButtonInfo sender)
        {
            #region 按钮权限
            // if (!BuildSqlHelper.IsExistList("FAMA_Account_Basic_Info")) return;
            #endregion
            // xtraTabPage1.PageEnabled = false;
            xtraTabPage2.PageEnabled = true;
            xtraTabPage2.PageVisible = true;
            IsEdit = "Add";
            //GetSearchLookUpEdit();
            Initiallize();
            base.DoAdd(sender);
        }
        //初始化新增信息
        public void Initiallize()
        {
            EDIT_MACHINE_NO.Text = "";//设备编号
            EDIT_MACHINE_DWG_PATH.Text = "";//设备图片
            EDIT_USE_RULES_PATH.Text = "";//设备位置
            EDIT_MACHINE_INFO_PATH.Text = "";//设备资料 
            strPath = "";
            strPath1 = "";
            strPath2 = "";
            IsEdit = "";
        }
        //绑定设备编号值
        public void GetSearchLookUpEdit()
        {
            string sql = @" SELECT MACHINE_NO,MACHINE_NAME,MACHINE_DESC FROM [LamexMESManager].[dbo].[FAMA_Account_Basic_Info]";
            DataTable dt = BaseBuildSql.GetDataTableBySql(sql);
            EDIT_MACHINE_NO.Properties.ValueMember = "MACHINE_NO";
            EDIT_MACHINE_NO.Properties.DisplayMember = "MACHINE_NO";
            EDIT_MACHINE_NO.Properties.DataSource = dt;
            txtMACHINE_NO.Properties.ValueMember = "MACHINE_NO";
            txtMACHINE_NO.Properties.DisplayMember = "MACHINE_NO";
            txtMACHINE_NO.Properties.DataSource = dt;
        }
        //编辑
        public override void DoEdit(Lamex.Interface.IButtonInfo sender)
        {
            if (gridView1.SelectedRowsCount == 0)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("【没有选中要修改的数据！】", "提示", MessageBoxButtons.OK);
                return;
            }
            int m = gridView1.FocusedRowHandle;
            DataRow dr = gridView1.GetDataRow(m);
            KeysName = dr["IDNO"].ToString();
            xtraTabPage1.PageEnabled = false;
            xtraTabPage2.PageEnabled = true;
            xtraTabPage2.PageVisible = true;
            IsEdit = "Edit";
           // GetSearchLookUpEdit();

            //加载数据
            // EDIT_MACHINE_NO.EditValue = dr["MACHINE_NO"].ToString();//设备编号
            EDIT_MACHINE_NO.Text = dr["MACHINE_NO"].ToString();
            EDIT_MACHINE_DWG_PATH.Text = dr["MACHINE_DWG_PATH"].ToString();//设备图片
            EDIT_USE_RULES_PATH.Text = dr["USE_RULES_PATH"].ToString();//使用规章
            EDIT_MACHINE_INFO_PATH.Text = dr["MACHINE_INFO_PATH"].ToString();//设备资料        
            base.DoEdit(sender);
        }
        //保存
        public override void DoSave(Lamex.Interface.IButtonInfo sender)
        {
            try
            {
                if (string.IsNullOrEmpty(EDIT_MACHINE_NO.Text))
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("设备编号不能为空", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                string UPDATE_USER = Lamex.Common.Loginer.CurrentUser.Account;//修改人
                if (IsEdit == "Add")
                {
                    string sql_Insert = "";
                    string STRMACHINE_NO = EDIT_MACHINE_NO.Text;//设备编号
                    string STRMACHINE_DWG_PATH = EDIT_MACHINE_DWG_PATH.Text;//设备图片
                    string[] STRUSE_RULES_PATH = EDIT_USE_RULES_PATH.Text.Split(new string[] { "\r\n" }, StringSplitOptions.None);//设备位置
                    string[] STRMACHINE_INFO_PATH = EDIT_MACHINE_INFO_PATH.Text.Split(new string[] { "\r\n" }, StringSplitOptions.None);//设备资料

                    if (STRUSE_RULES_PATH.Length >= STRMACHINE_INFO_PATH.Length && STRUSE_RULES_PATH.Length > 1)
                    {
                        // int k = 0;
                        for (int i = 0; i < STRUSE_RULES_PATH.Length - 1; i++)
                        {
                            if (STRMACHINE_INFO_PATH.Length >= i + 1)
                            {
                                // k++;
                                sql_Insert = sql_Insert + ";" + @"INSERT INTO [LamexMESManager].[dbo].[FAMA_File_Path_Info]( [MACHINE_NO]
      ,[MACHINE_DWG_PATH]
      ,[USE_RULES_PATH]
      ,[MACHINE_INFO_PATH]
      ,[UPDATE_TIME]
      ,[UPDATE_USER])
	  VALUES('" + STRMACHINE_NO + "','" + STRMACHINE_DWG_PATH + "','" + STRUSE_RULES_PATH[i] + "','" + STRMACHINE_INFO_PATH[i] +
                  "', GETDATE(),'" + UPDATE_USER + "')";
                            }
                            else
                            {
                                sql_Insert = sql_Insert + ";" + @"INSERT INTO [LamexMESManager].[dbo].[FAMA_File_Path_Info]( [MACHINE_NO]
      ,[MACHINE_DWG_PATH]
      ,[USE_RULES_PATH]
      ,[MACHINE_INFO_PATH]
      ,[UPDATE_TIME]
      ,[UPDATE_USER])
	  VALUES('" + STRMACHINE_NO + "','" + STRMACHINE_DWG_PATH + "','" + STRUSE_RULES_PATH[i] + "','" + "" +
                  "', GETDATE(),'" + UPDATE_USER + "')";
                            }
                        }
                    }

                    else if (STRMACHINE_INFO_PATH.Length > STRUSE_RULES_PATH.Length)
                    {
                        // int k = 0;
                        for (int i = 0; i < STRMACHINE_INFO_PATH.Length - 1; i++)
                        {
                            if (STRUSE_RULES_PATH.Length >= i + 1)
                            {
                                // k++;
                                sql_Insert = sql_Insert + ";" + @"INSERT INTO [LamexMESManager].[dbo].[FAMA_File_Path_Info]( [MACHINE_NO]
      ,[MACHINE_DWG_PATH]
      ,[USE_RULES_PATH]
      ,[MACHINE_INFO_PATH]
      ,[UPDATE_TIME]
      ,[UPDATE_USER])
	  VALUES('" + STRMACHINE_NO + "','" + STRMACHINE_DWG_PATH + "','" + STRUSE_RULES_PATH[i] + "','" + STRMACHINE_INFO_PATH[i] +
                  "', GETDATE(),'" + UPDATE_USER + "')";
                            }
                            else
                            {
                                sql_Insert = sql_Insert + ";" + @"INSERT INTO [LamexMESManager].[dbo].[FAMA_File_Path_Info]( [MACHINE_NO]
      ,[MACHINE_DWG_PATH]
      ,[USE_RULES_PATH]
      ,[MACHINE_INFO_PATH]
      ,[UPDATE_TIME]
      ,[UPDATE_USER])
	  VALUES('" + STRMACHINE_NO + "','" + STRMACHINE_DWG_PATH + "','','" + STRMACHINE_INFO_PATH[i] + "', GETDATE(),'" + UPDATE_USER + "')";
                            }
                        }
                    }
                    else
                    {
                        sql_Insert = sql_Insert + ";" + @"INSERT INTO [LamexMESManager].[dbo].[FAMA_File_Path_Info]( [MACHINE_NO]
      ,[MACHINE_DWG_PATH]
      ,[USE_RULES_PATH]
      ,[MACHINE_INFO_PATH]
      ,[UPDATE_TIME]
      ,[UPDATE_USER])
	  VALUES('" + STRMACHINE_NO + "','" + STRMACHINE_DWG_PATH + "','','', GETDATE(),'" + UPDATE_USER + "')";
                    }
                    if (BaseBuildSql.ExecuteNonQuery(sql_Insert) > 0)

                        DevExpress.XtraEditors.XtraMessageBox.Show("新增成功", "提示", MessageBoxButtons.OK);
                    else
                        DevExpress.XtraEditors.XtraMessageBox.Show("新增失败", "提示", MessageBoxButtons.OK);
                }
                if (IsEdit == "Edit")
                {

                    string sql_Update = @"UPDATE [LamexMESManager].[dbo].[FAMA_File_Path_Info] SET 
      [MACHINE_DWG_PATH]='" + EDIT_MACHINE_DWG_PATH.Text + @"'
      ,[USE_RULES_PATH]='" + EDIT_USE_RULES_PATH.Text + @"'
      ,[MACHINE_INFO_PATH]='" + EDIT_MACHINE_INFO_PATH.Text + @"'
      ,[UPDATE_TIME]=GETDATE()
      ,[UPDATE_USER]='" + UPDATE_USER + "' WHERE IDNO='" + KeysName + "' AND MACHINE_NO='" + EDIT_MACHINE_NO.Text + "'";
                    if (BaseBuildSql.ExecuteNonQuery(sql_Update) > 0)
                        DevExpress.XtraEditors.XtraMessageBox.Show("修改成功", "提示", MessageBoxButtons.OK);
                    else
                        DevExpress.XtraEditors.XtraMessageBox.Show("修改失败", "提示", MessageBoxButtons.OK);
                }

                xtraTabPage2.PageEnabled = false;
                xtraTabPage1.PageEnabled = true;
                DoView(null);
                Initiallize();
                base.DoSave(sender);

            }
            catch (Exception ex)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        public override void DoExport(IButtonInfo sender)
        {
            if (!Directory.Exists(@"D:\MESTemp"))
                Directory.CreateDirectory(@"D:\MESTemp");
            SaveFileDialog fileDialog = new SaveFileDialog();
            fileDialog.Title = "导出Excel";
            fileDialog.InitialDirectory = @"D:\MESTemp";//导出默认路径
            fileDialog.Filter = "Excel文件(*.xlsx)|*.xlsx";//导出默认格式
            fileDialog.FileName = "MES_TEMP_" + DateTime.Now.ToString("yyMMdd_hhMMss");//导出默认名称
            DialogResult dialogResult = fileDialog.ShowDialog(this);
            if (dialogResult == DialogResult.OK)
            {
                //导出表【IE_Part_TaskList】中当前产品类型，无“工艺路线标识”的数据

                string sqlWhere = "";
                string sql = @" SELECT IDNO,[MACHINE_NO]
      ,[MACHINE_DWG_PATH]
      ,[USE_RULES_PATH]
      ,[MACHINE_INFO_PATH]
      ,[UPDATE_TIME]
      ,[UPDATE_USER]
  FROM [LamexMESManager].[dbo].[FAMA_File_Path_Info] WHERE 1=1";
                if (!string.IsNullOrEmpty(txtMACHINE_NO.Text))
                {
                    sqlWhere += " and MACHINE_NO like '%" + txtMACHINE_NO.Text + "%'";
                }
                sql = sql + sqlWhere + " order by UPDATE_TIME desc ";
                DataTable dtList = BaseBuildSql.GetDataTableBySql(sql);

                GridControl grid = new GridControl();
                GridView view = new GridView();        
                grid.ViewCollection.Add(view);
                grid.MainView = view;
                view.GridControl = grid;
                foreach (DataColumn dc in dtList.Columns)
                {
                    DevExpress.XtraGrid.Columns.GridColumn gridColumnNumber = view.Columns.AddVisible(dc.ColumnName);
                    gridColumnNumber.FieldName = dc.ColumnName;
                }
                grid.DataSource = dtList;
                this.Controls.Add(grid);
                grid.ForceInitialize();//强制初始化
                //Font font = new Font("宋体", 11, FontStyle.Bold); 
                //view.Appearance.HeaderPanel.Font = font;
                //view.Appearance.Row.Font = font;            
                view.BestFitColumns();
                view.OptionsView.ColumnAutoWidth = false;
                view.OptionsView.ShowAutoFilterRow = false;
                view.OptionsPrint.PrintHorzLines = false;//去掉水平网格线
                view.OptionsPrint.PrintVertLines = false;//去掉垂直网格线
                view.ExportToXlsx(fileDialog.FileName);
                if (DevExpress.XtraEditors.XtraMessageBox.Show("导出成功，是否打开文件？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                    System.Diagnostics.Process.Start(fileDialog.FileName);//打开指定路径下的文件

            }
        }
        private void BTN_MACHINE_DWG_PATH_Click(object sender, EventArgs e)
        {
            strPath = SelectPath_DWG();
            EDIT_MACHINE_DWG_PATH.Text = strPath;
        }

        private void BTN_USE_RULES_PATH_Click(object sender, EventArgs e)
        {
            strPath1 = strPath1 + SelectPath() + "\r\n";
            EDIT_USE_RULES_PATH.Text = strPath1;
        }

        private void BTN_MACHINE_INFO_PATH_Click(object sender, EventArgs e)
        {
            strPath2 = strPath2 + SelectPath() + "\r\n";
            EDIT_MACHINE_INFO_PATH.Text = strPath2;
        }
        private string SelectPath()
        {
            string path = string.Empty;
            var openFileDialog = new OpenFileDialog()
            {
                Filter = "Files (*.*)|*.*"//如果需要筛选txt文件（"Files (*.txt)|*.txt"）
            };
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                path = openFileDialog.FileName;
            }
            return path;
        }
        private string SelectPath_DWG()
        {
            string path = string.Empty;
            var openFileDialog = new OpenFileDialog()
            {
                Filter = "Files (*.*)|*.jpg;*.png;*.gif;*.jpeg;*.tif;*.bmp"//"Files (*.*)|*.*"//如果需要筛选txt文件（"Files (*.txt)|*.txt"）
            };
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                path = openFileDialog.FileName;
            }
            return path;
        }
        private void gridView1_DoubleClick(object sender, EventArgs e)
        {
            DoEdit(null);
        }
    }
}
